# coding=utf-8
import pymysql.cursors


# Connect to the database
def link_mysql():
    return pymysql.connect(host='localhost',
                           user='root',
                           password='123456',
                           db='bbf41',
                           charset='utf8',
                           cursorclass=pymysql.cursors.DictCursor)


def exec_sql(conn, sql, commit=False):
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
        if commit:
            conn.commit()
    finally:
        conn.close()


def query_all(conn, sql):
    try:
        with conn.cursor() as cursor:
            rn = cursor.execute(sql)
            result = None
            if rn > 0:
                result = cursor.fetchall()
            return result
    finally:
        conn.close()


def get_value_by_key(conn, key):
    try:
        with conn.cursor() as cursor:
            sql = 'SELECT * FROM key_value_pair WHERE idx="%s"' % key
            rn = cursor.execute(sql)
            result = None
            if rn > 0:
                result = cursor.fetchone()
            return result
    finally:
        conn.close()


def join_dict(save_dict, quote_type='"'):
    frag = ''
    tmp_list = []
    for (k, v) in save_dict.items():
        tmp_list.append(k + '=' + quote_type + str(v) + quote_type)
    if len(tmp_list):
        frag = str.join(',', tmp_list)
    return frag
